package com.zon.len.dynamic;

import com.zon.len.dynamic.DynamicDruidDataSource.DynamicDataSourceKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZonLen since on 2021/12/31 上午10:33
 */
@Slf4j
public class DataSourceContextHolder {

  private static final ThreadLocal<DynamicDataSourceKey> DATASOURCE_KEY = new ThreadLocal<>();

  /**
   * 可以自定义手动切换，但是也需要手动清除线程缓存
   */
  public static void switchDataSource(DynamicDataSourceKey sourceType) {
    if (DATASOURCE_KEY.get() == null) {
      DATASOURCE_KEY.set(sourceType);
    }
  }


  public static DynamicDataSourceKey getDataSourceKey() {
    final DynamicDataSourceKey dynamicDataSourceKey = DATASOURCE_KEY.get();
    if (log.isDebugEnabled()) {
      log.debug("Current mybatis statement execute datasource key: {}",
          dynamicDataSourceKey == null ? DynamicDataSourceKey.DEFAULT_DB.name()
              : dynamicDataSourceKey.name());
    }
    if (null == dynamicDataSourceKey) {
      return DynamicDataSourceKey.DEFAULT_DB;
    }
    return dynamicDataSourceKey;
  }

  public static void release() {
    DATASOURCE_KEY.remove();
  }
}
